import React from "react";
import "./swarchbar.css";

class SearchBar extends React.Component {
  //构造函数
  constructor() {
    super(); //调用父类的构造函数
    this.state = {
      isShow: false,
      history: ["汉堡", "炸鸡", "冰激凌", "肥宅水"],
      enterIndex:-1,
      selectIndex:-1,
    };
  }
  //渲染函数
  render() {
    return (
      <div className="search_bar">
        <div className="search_bar_dv1">
          <input
            type="text"
            onFocus={() => {
              this.setState({
                isShow: true,
              });
            }}
            onBlur={() => {
              this.setState({
                isShow: false,
              });
            }}
            onKeyDown={(event)=>{
                var keyCode=event.keyCode;
                // console.log(keyCode);
                if(keyCode===38){
                    this.state.selectIndex--

                    if(this.state.selectIndex<0){
                        this.state.selectIndex=this.state.history.length-1
                    }
                    this.setState({
                        selectIndex:this.state.selectIndex
                    })
                    this.refs.input.value=this.state.history[this.state.selectIndex]


                }else if(keyCode===40){
                    this.state.selectIndex++
                    if(this.state.selectIndex>this.state.history.length-1){
                        this.state.selectIndex=0
                    }
                    this.setState({
                        selectIndex:this.state.selectIndex
                    })
                    this.refs.input.value=this.state.history[this.state.selectIndex]
                }
            }}
            ref="input"
          ></input>
          <button
            onClick={() => {
              console.log(this.refs.input);
              //   var value=this.refs.input.value
            }}
          >
            百度一下
          </button>
        </div>
        <div
    
          className={
            this.state.isShow ? "search_bar_dv2" : "search_bar_dv2_fls"
          }
        >
          {this.state.history.map((element, index) => {
            return <div key={index}
            className={this.state.enterIndex===index?"search_history_hover":"search_history"}
            onMouseEnter={()=>{
                this.setState({
                    enterIndex:index
                })
            }}>{element}</div>;
          })}
        </div>
      </div>
    );
  }
}
export default SearchBar;
